package com.life.wd.service.Imp;

import com.life.wd.constant.MessageConstant;
import com.life.wd.constant.StatusConstant;
import com.life.wd.dto.EmployeeDTO;
import com.life.wd.dto.EmployeeLoginDTO;
import com.life.wd.entity.Employee;
import com.life.wd.exception.CommonException;
import com.life.wd.mapper.EmployeeMapper;
import com.life.wd.repository.EmployeeRepository;
import com.life.wd.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
public class EmployeeServiceImp implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private EmployeeRepository employeeRepository;
    private static final String DEFAULT_PASSWORD = "123456";
    @Override
    public Employee loginService(EmployeeLoginDTO employeeLoginDTO) throws Exception {
        String username = employeeLoginDTO.getUsername();
        Employee emp = employeeRepository.findByUsername(username);
        if(emp == null) throw new CommonException(404,MessageConstant.ACCOUNT_NOT_FOUND);
        String password = employeeLoginDTO.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if(!password.equals(emp.getPassword())) throw new CommonException(401,MessageConstant.PASSWORD_ERROR);
        return emp;
    }

    @Override
    public void insert(EmployeeDTO employeeDTO) {
        Employee emp = new Employee();
        BeanUtils.copyProperties(employeeDTO,emp);
        emp.setStatus(StatusConstant.ENABLE);
        emp.setPassword(DigestUtils.md5DigestAsHex(DEFAULT_PASSWORD.getBytes()));
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        employeeMapper.insert(emp);
    }
}
